<template>
    <div class="to-from-pie-chart">
        <div ref="chartRef" style="width: 100%;height:230px"></div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { ECharts } from 'echarts/core'

// 注册组件
echarts.use([PieChart, TooltipComponent, LegendComponent, TitleComponent, CanvasRenderer])

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: ECharts | null = null

// 接收父组件传入的 props
const { title, data } = defineProps<{
  title: string
  data: { name: string; value: number }[]
}>()

// 自动刷新图表
watch(() => data, () => {
  if (myChart) {
    myChart.setOption(getOption())
  }
}, { deep: true })

onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value)
    myChart.setOption(getOption())
  }
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  myChart?.dispose()
})

function resizeChart() {
  myChart?.resize()
}

function getOption() {
  return {

    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      // type:'scroll',
      top: 155,
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 3,
      formatter: (name: string) => {
        const item = data.find(d => d.name === name)
        return `{normal|${name}}  {bold|${item?.value ?? ''}%}`
      },
      textStyle: {
        fontSize: 14,
        rich: {
          normal: {
            color: '#4E718F',
            fontWeight: 'normal'
          },
          bold: {
            color: '#4E718F',
            fontWeight: 'bold',
          }
        }
      }
    },
    series: [
      // 灰色背景圆环
      {
        type: 'pie',
        radius: 75,
        center: ['50%', 75],
        silent: true, // 禁用交互
        legendHoverLink: false,// 禁用图例悬停高亮
        label: { show: false },
        data: [{ value: 100, name: '', itemStyle: { color: '#d4e5f8' } }],
        z: 1
      },
      // 实际数据饼图
      {
        name: title,
        top:'top',
        type: 'pie',
        radius: [26, 62],
        center: ['50%', 75],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'center',
          formatter: title.replace(/ /g, '\n'),
          fontSize: 8,
          lineHeight: 11,
          color: '#4E718F',
          fontWeight: 'bold'
        },
        labelLine: {
          show: false
        },
        data,
        color: ['#4B81FF', '#3EC86C', '#FFA800', '#E952BB'] // 蓝 绿 黄 粉
      }
    ]
  }
}
</script>


<style lang="less" scoped>
.to-from-pie-chart{
  flex:1;
}
</style>